package cn.gjxblog.service.impl;


import cn.gjxblog.common.model.PageCondition;
import cn.gjxblog.model.dto.HouseQueryDTO;
import cn.gjxblog.model.entity.House;
import cn.gjxblog.service.HouseService;
import cn.gjxblog.service.RecommendService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2018/12/25 13:46
 */
@Service
public class RecommendServiceImpl implements RecommendService {

    private static final String HOT_HOUSE_KEY = "_hot_house";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private HouseService houseService;

    @Override
    public List<House> queryHotHouses(Integer size) {
        Set<String> idSet = redisTemplate.opsForZSet().reverseRange(HOT_HOUSE_KEY, 0, -1);
        int i = 0;
        List<House> list = new LinkedList<>();
        for (String s : idSet) {
            if(i>size){

                break;
            }
            House house = houseService.getHouse(s);
            list.add(house);
            i++;

        }

        return list;
    }

    @Override
    public void increaseHot(String id) {
            redisTemplate.opsForZSet().incrementScore(HOT_HOUSE_KEY,id,1.0D);
    }

    @Override
    public List<House> queryLastestHouses() {
        HouseQueryDTO houseQueryDTO = new HouseQueryDTO();
        PageCondition pageCondition = new PageCondition();
        pageCondition.setSort("create_time");
        pageCondition.setPageNum(1);
        pageCondition.setPageSize(6);
        houseQueryDTO.setPageCondition(pageCondition);

        PageInfo pageInfo = houseService.searchHouses(houseQueryDTO);
        return pageInfo.getList();
    }


    @Override
    public List<House> queryGoodHouses() {
        HouseQueryDTO houseQueryDTO = new HouseQueryDTO();
        PageCondition pageCondition = new PageCondition();
        pageCondition.setSort("rating");
        pageCondition.setPageNum(1);
        pageCondition.setPageSize(4);
        houseQueryDTO.setPageCondition(pageCondition);

        PageInfo pageInfo = houseService.searchHouses(houseQueryDTO);
        return pageInfo.getList();
    }

    @Override
    public void removeHouse(String houseId) {
        redisTemplate.opsForZSet().remove(HOT_HOUSE_KEY,houseId);
    }
}
